package com.app.myApp.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 文件文本提取工具类（支持TXT/PDF/DOCX）
 */
@Component
public class FileTextExtractor {

    /**
     * 提取文件文本（根据MIME类型适配）
     * @param fileBytes 文件字节数组（从COS下载）
     * @param mimeType 文件MIME类型（如application/pdf）
     * @return 提取的纯文本
     * @throws Exception 提取失败异常
     */
    public String extractText(byte[] fileBytes, String mimeType) throws Exception {
        if (fileBytes == null || fileBytes.length == 0) {
            return "";
        }

        // 根据MIME类型选择提取逻辑
        switch (mimeType) {
            case "text/plain": // TXT
                return new String(fileBytes, StandardCharsets.UTF_8);

            case "application/pdf": // PDF
                return extractPdfText(fileBytes);

            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": // DOCX
                return extractDocxText(fileBytes);

            default:
                throw new Exception("不支持的文件类型：" + mimeType);
        }
    }

    /**
     * 提取PDF文本
     */
    private String extractPdfText(byte[] pdfBytes) throws Exception {
        try (InputStream is = new ByteArrayInputStream(pdfBytes);
             PDDocument document = PDDocument.load(is)) {
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(document); // 提取全部文本
        }
    }

    /**
     * 提取DOCX文本
     */
    private String extractDocxText(byte[] docxBytes) throws Exception {
        try (InputStream is = new ByteArrayInputStream(docxBytes);
             XWPFDocument document = new XWPFDocument(is)) {
            StringBuilder text = new StringBuilder();
            // 遍历文档段落提取文本
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                text.append(paragraph.getText()).append("\n");
            }
            return text.toString().trim();
        }
    }
}